﻿using AnalyStock.DataAnalysis;
using static AnalyStock.DataAnalysis.DataCollection;
using AnalyStock.DataManage;
using Microsoft.Win32;

namespace AnalyStock.WPFPage;

public partial class SelectStockPage : Page
{
    private DownloadProgress doWorkProgress;

    /// <summary>
    ///     选股页面控制操作
    /// </summary>

    #region

    public SelectStockPage()
    {
        InitializeComponent();
        LstSele.ItemsSource = SeleStockTactics.GetTacticNames();
        DViewSeleStock.SelectionChanged += SeleStock_SelectionChanged;
        BtnExecSelect.Click += BtnExecSelect_Click;
         //打开自选分类窗口菜单，点击鼠标右手键
        ChartKline.IsAddSeleStockMenuItem=true;
    }

    private void SeleStock_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if (DViewSeleStock.CurrentItem is not StockKeyIndicators item)
        {
            return;
        }

        ChartKline.ChangeCurrentStock(item.StockCode);
    }

    private void BtnDelCurrentStock_Click(object sender, RoutedEventArgs e)
    {
        if (ChartKline.GetCurrentStockInfo() is not StockInfo currBakdaiy)
        {
            return;
        }

        var currentStock = SeleStockKeyIndicators.First(n => n.StockCode == currBakdaiy.Ts_code);
        if (currentStock is not null)
        {
            if ("是否确认删除该自选股?".IsConfirmMessage())
            {
                SeleStockKeyIndicators.Remove(currentStock);
            }

            DViewSeleStock.ItemsSource = default;
            DViewSeleStock.ItemsSource = SeleStockKeyIndicators;
        }
    }

    private void BtnExportData_Click(object sender, RoutedEventArgs e)
    {
        if (!SeleStockKeyIndicators.Any())
        {
            return;
        }

        if ("是否保存选择股，是否同意?".IsConfirmMessage())
        {
            var seleStocks = (sender as Button) switch
            {
                { Name: nameof(BtnExportAllData) } => SeleStockKeyIndicators
                    .OrderByDescending(n => (n.Industry, n.LastEps)),
                { Name: nameof(BtnExportSeleData) } => SeleStockKeyIndicators
                    .Where(n => n.IsSelect)
                    .OrderByDescending(n => (n.Industry, n.LastEps)),
                _ => throw new Exception("无股票选择数据...")
            };
            SaveFileDialog dialog = new()
            {
                Filter = "CSV文件(*.CSV,*.csv)|*.CSV;*.csv"
            };
            _ = dialog.ShowDialog();
            CsvDataManage.SaveDataToCSV(seleStocks, dialog.FileName);
            $"数据保存到{dialog.FileName},处理完毕...".NotifyMessage();
        }
    }

    #endregion

    /// <summary>
    ///     执行选股
    /// </summary>
    /// <param name=></param>

    #region

    private async void BtnExecSelect_Click(object sender, RoutedEventArgs e)
    {
        if (doWorkProgress is null)
        {
            InitializeDowork();
        }
        if (!doWorkProgress.IsBusy)
        {
            await StartDoworking();
        }
        else
        {
            doWorkProgress.Cancel();
        }
    }

    private async Task StartDoworking()
    {
        try
        {
            await DoworkToSelectAsync(doWorkProgress, LstSele.SelectedIndex, doWorkProgress.Token);
        }
        catch (Exception ex)
        {
            doWorkProgress.Cancel();
            ex.Message.ErrorMessage();
        }
        finally
        {
            DoworkCompleted();
        }

    }

    private static async Task DoworkToSelectAsync(IDownloadProgress progress,
                                                  int seleTacticIdx,
                                                  CancellationToken token)
    {
        var stockInfos = await FilltoStockInfosAsync().ConfigureAwait(false);
        if (stockInfos.IsNullOrEmpty())
        {
            throw new Exception("加载全部股票基础信息错误...");
        }
        var stockinfosCount = stockInfos.Count();

        await foreach (var index in SelectAsyncEnumerable().ConfigureAwait(false))
        {
            //后台反馈前窗口UI更新
            progress.Report(null, index * 100 / stockinfosCount,
                $"第:{index}共{stockinfosCount}只股票，选出:{SeleStockKeyIndicators.Count}只股票...");
            if (token.IsCancellationRequested)
            {
                //进度填写100，通知进度器，任务已经退出了。进度器将busys状态初始化为false
                progress.Report(null, 100,
                    $"第:{index}共{stockinfosCount}只股票，选出:{SeleStockKeyIndicators.Count}只股票...");
                throw new TaskCanceledException();
            }
        }
        return;
        async IAsyncEnumerable<int> SelectAsyncEnumerable()
        {
            var index = 1;
            foreach (var item in stockInfos)
            {
                await SeleStockTactics.DoWorkOnTacticAsync(seleTacticIdx, item)
                                      .ConfigureAwait(false);
                yield return index++;
            }
        }
    }

    private void InitializeProgress()
    {
        DisposeProgress();
        doWorkProgress = new();
        doWorkProgress.ProgressChanged += (s, e) =>
        {
            LbProgress.Content = e.UserState;
            
           // ApplicationParam.IsBusyOfBackgroundWorking = e.ProgressPercentage < 100;
        };
    }
    private void DisposeProgress()
    {
        if (doWorkProgress is not null)
        {
            doWorkProgress.Dispose();
            doWorkProgress = null;
        }
    }

    private void InitializeDowork()
    {
        //初始化错误记录和选股记录集
        ErrorLogPool.ErrorLogs ??= new List<ErrorLog>();
        ErrorLogPool.ErrorLogs.Clear();
        SeleStockKeyIndicators ??= new List<StockKeyIndicators>();
        SeleStockKeyIndicators.Clear();
        LstSele.IsEnabled = false;
        //初始化进度跟踪器
        InitializeProgress();
        //设置暂停标志
        BtnExecSelect.Content = "II";
    }

    private void DoworkCompleted()
    {
        LbProgress.Content = doWorkProgress.IsCancel
            ? $"执行中止,选择{SeleStockKeyIndicators.Count}只股票"
            : $"执行完成,选择{SeleStockKeyIndicators.Count}只股票";
        DViewSeleStock.ItemsSource = SeleStockKeyIndicators;
        LstSele.IsEnabled = true;
        BtnExecSelect.Content = "▶";
        DisposeProgress();
    }
    #endregion
}